import 'dart:io';

import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:open_file/open_file.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

class ApkUtils {
  // 私有构造函数
  ApkUtils._internal();

  // 静态变量，用于存储单例实例
  static final ApkUtils _instance = ApkUtils._internal();

  // 获取单例实例的静态方法
  static ApkUtils get instance => _instance;

  //安装应用
  void installApk(String apkPath) {
    if (Platform.isAndroid) {
      Permission.requestInstallPackages.request().then((value) {
        if (value.isGranted) {
          OpenFile.open(apkPath).then((onValue) {
            print("${onValue.type}  ${onValue.message}");
          });
        } else {
          Fluttertoast.showToast(msg: "请允许安装应用权限");
        }
      });
    } else {}
  }

  //获取文件后缀名
  String getPathFileName(file) {
    if (file == null || file.isEmpty) {
      return "";
    }
    var lastIndexOf = file.toString().lastIndexOf("/");
    return file.toString().substring(lastIndexOf, file.toString().length);
  }

  String getFileTypeName(file) {
    return path.extension(file);
  }

  Future<String> requestExternalStorageDirectory() async {
    var directory = await getExternalStorageDirectory();
    return directory!.path;
  }

  void downloadTaskId(String apkUrl, savePath) async {
    var map = await initPlatformState();
    var s = await requestExternalStorageDirectory();
    var appName = map['appName'];
    var version = map['version'];
    var buildNumber = map['buildNumber'];
    if (await Permission.storage.request().isGranted) {
      ensureDirectoryExists(savePath);
      registerDownloaderTask(apkUrl, savePath);
      // 权限已授予
      final taskId = await FlutterDownloader.enqueue(
        url: apkUrl,
        headers: {},
// optional: header send with url (auth token etc)
        savedDir: savePath,
        showNotification: true,
// show download progress in status bar (for Android)
        openFileFromNotification: true, // click on notification to open downloaded file (for Android)
      );
    } else {
      // 权限被拒绝
      Fluttertoast.showToast(msg: "存储权限获取失败!");
    }
  }

  Future<void> registerDownloaderTask(String apkUrl, savePath) async {
    //TODO 下载问题
    void downloadCallback(id, status, progress) {
      print('-------------------------------Download task ($id) is in status ($status) and process ($progress)');
      if (status == DownloadTaskStatus.complete) {
        ApkUtils.instance.installApk("${savePath}/${ApkUtils.instance.getPathFileName(apkUrl)}");
      }
    }

    await FlutterDownloader.registerCallback(downloadCallback);
  }

  /**
   * 判断版本号是否更新
   */
  bool isNewVersion(String netVersion, String localVersion) {
    if (netVersion == localVersion) {
      return false;
    }
    if (netVersion.isEmpty || localVersion.isEmpty) {
      return false;
    }
    var netVersionList = netVersion.split(".");
    var localVersionList = localVersion.split(".");
    //比较大小
    for (var i = 0; i < netVersionList.length; i++) {
      var netVersionInt = int.parse(netVersionList[i]);
      var localVersionInt = int.parse(localVersionList[i]);
      if (netVersionInt > localVersionInt) {
        return true;
      } else if (netVersionInt < localVersionInt) {
        return false;
      }
    }
    // 如果所有部分都相等，检查长度
    return netVersionList.length > localVersionList.length;
  }

  static void ensureDirectoryExists(String apkUrl) {
    Directory directory = Directory(apkUrl);
    if (!directory.existsSync()) {
      directory.createSync(recursive: true);
    }
  }

  Future<Map<String, dynamic>> initPlatformState() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String appName = packageInfo.appName;
    String packageName = packageInfo.packageName;
    String version = packageInfo.version;
    String buildNumber = packageInfo.buildNumber;
    print("-------------");
    print('App Name: $appName');
    print('Package Name: $packageName');
    print('Version: $version');
    print('Build Number: $buildNumber');
    print("-------------");
    var map = <String, dynamic>{
      'appName': packageInfo.appName,
      'packageName': packageInfo.packageName,
      'version': packageInfo.version,
      'buildNumber': packageInfo.buildNumber
    };
    return map;
  }
}
